using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Soveryn.Commerce.API;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Pages
{
    public partial class CustomerAccount : AuthorizedAndSSLPageBaseClass
    {

        protected new void Page_PreInit(object sender, EventArgs e)
        {
            Website = WebsiteData.WebsiteDetail();
            PageID = Website.CheckoutTemplatePageID.Value;
            base.Page_PreInit(sender, e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            DataSet orderDS = null;
            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
            args.Add("CustomerCartSessionID", CustomerCartSessionID);
            APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "OrdersListForCustomer", args, false, false);
            if (env.response != null)
            {
                string response = (string)env.response;
                orderDS = new DataSet();
                orderDS.ReadXml(new StringReader((string)env.response));
            }

            if (DataUtils.HasRecords(orderDS, 0))
            {

                DataTable orderDT = orderDS.Tables[0];
                DataTable paymentsDT = orderDS.Tables[1];
                DataTable orderLinesDT = orderDS.Tables[2];

                OrdersRepeater.DataSource = orderDT;
                OrdersRepeater.DataBind();

            }

        }

        protected void OrdersRepeater_ItemDataBound(Object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;

            HyperLink OrderEditHyperLink = (HyperLink)e.Item.FindControl("OrderEditHyperLink");
            Label StatusLabel = (Label)e.Item.FindControl("StatusLabel");

            OrderProperties order = OrderProperties.Create(drv.Row);

            if (order.AmountToPay != 0)
            {
                OrderEditHyperLink.Text = "Pay (#" + order.OrderDisplayID.ToString() + ")";
                OrderEditHyperLink.NavigateUrl = "OrderCheckout.aspx?OrderID=" + order.OrderID;
                StatusLabel.Text = "Unpaid";
            }
            else
            {
                OrderEditHyperLink.Text = "View (#" + order.OrderDisplayID.ToString() + ")";
                OrderEditHyperLink.NavigateUrl = "OrderDetails.aspx?OrderID=" + order.OrderID;
                StatusLabel.Text = "Paid";
            }



        }

    }
}